package com.dkh.recommend.controller;

import cn.hutool.core.lang.UUID;
import com.dkh.recommend.dto.Result;
import com.dkh.recommend.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传到七牛云
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${oss.qiniu.url}")
    private String qiniuUrl;
    @Value("${oss.qiniu.accessKey}")
    private String accessKey;
    @Value("${oss.qiniu.secretKey}")
    private String secretKey;
    @Value("${oss.qiniu.bucket}")
    private String bucket;

    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {

        MultipartFile multipartFile =file;
        //        调用fileService上传文件
//        生成的文件名称fileName,要保证它的唯一
//        文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //        扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //        文件名称
        String fileName = UUID.randomUUID() + suffix;

        //        调用utils下的工具类 accessKey,secretKey,bucket,fileName
        try {
            QiniuUtils.upload2qiniu(accessKey,secretKey,bucket,multipartFile.getBytes(),fileName);
            String url = qiniuUrl+fileName;
            return Result.ok(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传文件失败！");
        }

    }



}
